﻿using System.Web.Mvc;
using HTB.DevFx;
using Maple.Weixin.MP.MvcExtension;

namespace Maple.Weixin.MP.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWeixinService weixin = ObjectService.GetObject<IWeixinService>();

        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(string signature, string timestamp, string nonce, string echoStr) {
            var sign = weixin.GetSignature(timestamp, nonce);
            if (sign == signature)
                return Content(echoStr);
            var content = string.Format("timestamp = {0}, nonce = {1}, token = {2}, sign = {3} || signature = {4}",
                timestamp, nonce, ((WeixinService) weixin).Token, sign, signature);
            return Content(content);
        }

        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(string signature, string timestamp, string nonce, string echoStr) {
            var sign = weixin.GetSignature(timestamp, nonce);
            if (sign != signature) {
                var content = string.Format("timestamp = {0}, nonce = {1}, token = {2}, sign = {3} || signature = {4}",
                    timestamp, nonce, ((WeixinService) weixin).Token, sign, signature);
                return Content(content);
            }

            var responseMessage = weixin.HandleMessage(Request);
            return new WeixinResult(responseMessage);
        }
    }
}
